<?php
    echo "<head>
        <title>Output</title>
        <link rel=\'stylesheet\' type=\'text/css\' href=\'../CSS/pages.css\'/>
        </head>
        <body>
        <table>";

    include 'dbconf.php';
    include 'dbopen.php';
    include 'functions.php';


	/*
	 * Get file locations from Misc/localization_files.txt
	 */

	$locFile = file("../Misc/localization_files.txt");
	foreach ($locFile as $locFileLine) {
    	if(substr($locFileLine,0,12) == "Rscript_path"){
    		$Rscript_path = trim(str_replace("=","",str_replace("Rscript_path","",$locFileLine))); 
    	}
	}


	if(file_exists("../Images/genes_vs_genotype.png")){
    	unlink("../Images/genes_vs_genotype.png");
	}
	if(file_exists("../TXT/raw_data.xls")){
    	unlink("../TXT/raw_data.xls");
	}
	
    $genotypeFile = "../TXT/genotype.txt";
    $fh = fopen($genotypeFile, 'w');
    fclose($fh);

    $explvlFile = "../TXT/explvl.txt";
    $fh = fopen($explvlFile, 'w');
    fclose($fh);
   
    
    $input_gene_sym = $_POST['input_gene_sym'];
    $input_gene_sym = preg_split('/\r/', $input_gene_sym);
    
    // Remove any empty rows or trailing newlines
    $input_gene_sym = removeEmptyRows($input_gene_sym);
    // Check for bogus gene symbols
    checkGeneSyms($input_gene_sym);

    $input_snp = $_POST['input_snp'];
    $input_snp = preg_split('/\r/', $input_snp);
    
    // Remove any empty rows or trailing newlines
    $input_snp = removeEmptyRows($input_snp);
    // Check for bogus SNP ID(s)
    checkSNPid($input_snp);

    $input_tissue = $_POST['bike_tissue'];
    $nbrOfInputGenes = sizeof($input_gene_sym);

    global $picnumber; $picnumber = 0;
    global $c;
    global $d;
    $c=0;


	$arrayOfExpValues = array();
	$arrayOfGenotypeValues = array();
	$annotationArray = array();

    while ($c < $nbrOfInputGenes) {

        $nbrOfInputSNPs = sizeof($input_snp);
        $d=0;
        foreach ($input_snp as $individual_snp) {

            $individual_snp = trim($individual_snp);
            $trimmed_genesym = trim($input_gene_sym[$c]);
            $probe_id_res = mysql_query(getProbeIdFromGeneSymbol($trimmed_genesym));
            $nrows_probe_id = mysql_numrows($probe_id_res);
            $l=0;

            while ($l < $nrows_probe_id) {

                $individual_probe_id = mysql_result($probe_id_res,$l,'probe_id');
                $individual_probe_id = trim($individual_probe_id);

                $joinQueryResult = mysql_query(getSNPGenoProExpl($individual_snp, $individual_probe_id, $input_tissue))
                        or die ("ERROR: could not send/execute query! ".  mysql_error());

                $nbrRowsJoinQuery=mysql_numrows($joinQueryResult);

                global $ind_nbr; $ind_nbr = "";
                global $ind_nbr_temp; $ind_nbr_temp = "";
                global $snp; $snp = "";
                global $exp_level; $exp_level = "";
                global $genotype; $genotype = "";
                global $el_temp; $el_temp = "";
                global $gt_temp; $gt_temp = "";
                global $snp_temp; $snp_temp = "";

                $k=0;
                while ($k < $nbrRowsJoinQuery) {
                    $snp_temp = mysql_result($joinQueryResult,$k,'snp');
                    $el_temp = mysql_result($joinQueryResult,$k,'exp_level');
                    $gt_temp = mysql_result($joinQueryResult,$k,'genotype');
                    $ind_nbr_temp = mysql_result($joinQueryResult,$k,'ind_nbr');

                    $snp = $snp . "\t" . $snp_temp;
                    $exp_level = $exp_level . "\t" . $el_temp;
                    $genotype = $genotype . "\t" . $gt_temp;
                    $ind_nbr = $ind_nbr . "\t" . $ind_nbr_temp;

                    $k++;
                }

                /*
                 * Not sure if removing the tab space in the beginning of
                 * the string is necessary
                 *
                 * The tab in the beginning of $snp and $probe_id is necessary to
                 * get the correct format
                 */
       
                $exp_level = preg_replace('/\t/', '', $exp_level,1);
                $genotype = preg_replace('/\t/', '', $genotype,1);
                $snp = preg_replace('/\t/', '', $snp,1);

				######################################################
				#Lasse:
				#Genotypes can also be TA, CA... etc - even though they are not in the present data set. They can even sometimes be "NA" (not found)
				#
				#I will just take them as they are, to avoid making any assumptions on how future array setups might give their data
				######################################################
#                if (preg_match('/A\/C/', $genotype) > 0) {
#                    $genotype = preg_replace('/A\/A/', 'AA', $genotype);
#                    $genotype = preg_replace('/A\/C/', 'AC', $genotype);
#                    $genotype = preg_replace('/C\/C/', 'CC', $genotype);
#
#                }
#
#                else if (preg_match('/A\/G/', $genotype) > 0) {
#                    $genotype = preg_replace('/A\/A/', 'AA', $genotype);
#                    $genotype = preg_replace('/A\/G/', 'AG', $genotype);
#                    $genotype = preg_replace('/G\/G/', 'GG', $genotype);
#
#                }
#
#                else if (preg_match('/A\/T/', $genotype) > 0) {
#                    $genotype = preg_replace('/A\/A/', 'AA', $genotype);
#                    $genotype = preg_replace('/A\/T/', 'AT', $genotype);
#                    $genotype = preg_replace('/T\/T/', 'TT', $genotype);
#                }
#
#                else if (preg_match('/C\/G/', $genotype) > 0) {
#                    $genotype = preg_replace('/C\/C/', 'CC', $genotype);
#                    $genotype = preg_replace('/C\/G/', 'CG', $genotype);
#                    $genotype = preg_replace('/G\/G/', 'GG', $genotype);
#                }
#

				$genotype_array = preg_split('/\t/', $genotype, -1, PREG_SPLIT_NO_EMPTY);
				$arrayOfGenotypeValues[$individual_snp] = $genotype_array;

#                $genotypeFile = "../TXT/genotype.txt";
#                $fh_genotypeFile = fopen($genotypeFile, 'w');
#                fwrite($fh_genotypeFile, $ind_nbr."\r");
#                fwrite($fh_genotypeFile, $individual_snp."\t");
#                fwrite($fh_genotypeFile, $genotype."\r");
#                fclose($fh_genotypeFile);

                $exp_level_array = preg_split('/\t/', $exp_level, -1, PREG_SPLIT_NO_EMPTY);
                $ind_nbr_array = preg_split('/\t/', $ind_nbr, -1, PREG_SPLIT_NO_EMPTY);

				$arrayOfExpValues[$individual_probe_id] = $exp_level_array;

#                $explvlFile = "../TXT/explvl.txt";
#                $fh_explvlFile = fopen($explvlFile, 'w');
#                fwrite($fh_explvlFile, "\t".$individual_probe_id."\r");
#
#                $nbrOfIndividuals = count($ind_nbr_array);
#                for ($counter=0; $counter < $nbrOfIndividuals; $counter++) {
#                    fwrite($fh_explvlFile, $ind_nbr_array[$counter]."\t");
#                    fwrite($fh_explvlFile, $exp_level_array[$counter]."\r");
#                }
#                fclose($fh_explvlFile);
#
#
#                /*
#                 * Start of Tissue file creation, thats going to be sent to R.
#                 */
#
#                $tissue_file = "../TXT/tissuetype.txt";
#                $fh_tissuefile = fopen($tissue_file, 'w');
#                fwrite($fh_tissuefile, $input_tissue."\r");
#                fclose($fh_tissuefile);

                /*
                 * Start of annotation file creation, thats going to be sent to R.
                 */

                $AnnotationQueryResult = mysql_query(getAnnotation($individual_probe_id))
                        or die ("ERROR: could not send/execute query getAnnotation!".  mysql_error());

                $temp1 = mysql_fetch_array($AnnotationQueryResult);
                $temp1['gene_sym'];
                
                $nbrRowsAnnotationQuery=mysql_numrows($AnnotationQueryResult);

                $probe_id_temp = "";
                $gene_sym_temp = "";
                $gene_name_temp = "";

                $k=0;
                while ($k < $nbrRowsAnnotationQuery) {
                    $probe_id_temp = mysql_result($AnnotationQueryResult,$k,'probe_id');
                    $gene_sym_temp = mysql_result($AnnotationQueryResult,$k,'gene_sym');
                    $gene_name_temp = mysql_result($AnnotationQueryResult,$k,'gene_name');

                    $k++;
                }
				
				
				$annotationArray[$probe_id_temp] = $gene_sym_temp."\t".$gene_name_temp;
                
                
#                $annotation_file = "../TXT/annotation.txt";
#                $fh_annotationfile = fopen($annotation_file, 'w');
#                fwrite($fh_annotationfile, "\tgenesymbol\tgenename\r");
#                fwrite($fh_annotationfile, $probe_id_temp . "\t" . $gene_sym_temp ."\t" . $gene_name_temp);
#                fclose($fh_annotationfile);
#
#
#                $gene_sym = $trimmed_genesym;
#
#                system("\"C:\Program Files\R\R-2.13.0\bin\Rscript.exe\" ../R/genes_vs_genotypes.R $picnumber");
#
#                $nocache = rand();
#
#                if ($picnumber % 4 == 0 && $picnumber != 0) {
#                    echo "</tr><tr><td><form method=\"post\" action=\"\"><input type=\"checkbox\" name=\"pic_id\" value=\"$picnumber\"></td>
#                              <td>
#                                <a href='../Images/genes_vs_genotypes$picnumber.png?$nocache'>
#                                    <img width=\"300\" height=\"300\" src='../Images/genes_vs_genotypes$picnumber.png?$nocache'>
#                                    </a>
#                                </td>";
#                }
#                
#                else {
#                    echo "<td><form method=\"post\" action=\"\"><input type=\"checkbox\" name=\"pic_id\" value=\"$picnumber\"></td>
#                              <td>
#                                  <a href='../Images/genes_vs_genotypes$picnumber.png?$nocache'>
#                                    <img width=\"300\" height=\"300\" src='../Images/genes_vs_genotypes$picnumber.png?$nocache'>
#                                    </a>
#                                </td>";
#                }
                $picnumber++;
                $l++;
            }
            $d++;
        }
        $c++;
    }


    
    /*
     * Start of Tissue file creation, thats going to be sent to R.
     */

    $tissue_file = "../TXT/tissuetype.txt";
    $fh_tissuefile = fopen($tissue_file, 'w');
    fwrite($fh_tissuefile, $input_tissue."\r");
    fclose($fh_tissuefile);
    


     /*
     * expression file
     */

    $explvlFile = "../TXT/explvl.txt";
    $fh_explvlFile = fopen($explvlFile, 'w');
    
    $probesetsToPrint = array_keys($arrayOfExpValues);
    foreach ($probesetsToPrint as $probeset) {
    	fwrite($fh_explvlFile, "\t"."X".$probeset);
    }
    fwrite($fh_explvlFile, "\r");


    $nbrOfIndividuals = count($ind_nbr_array);
    for ($counter=0; $counter < $nbrOfIndividuals; $counter++) {
        fwrite($fh_explvlFile, $ind_nbr_array[$counter]);
        foreach ($probesetsToPrint as $probeset) {
        	fwrite($fh_explvlFile, "\t".$arrayOfExpValues[$probeset][$counter]);
        	
        }
        fwrite($fh_explvlFile, "\r");
    }
    fclose($fh_explvlFile);
    
    
    
    
        
     /*
     * genotype file
     */

    $genotypeFile = "../TXT/genotype.txt";
    $fh_genotypeFile = fopen($genotypeFile, 'w');
    
    $snpsToPrint = array_keys($arrayOfGenotypeValues);
    foreach ($snpsToPrint as $snp) {
    	fwrite($fh_genotypeFile, "\t"."X".$snp);
    }
    fwrite($fh_genotypeFile, "\r");

    $nbrOfIndividuals = count($ind_nbr_array);
    for ($counter=0; $counter < $nbrOfIndividuals; $counter++) {
        fwrite($fh_genotypeFile, $ind_nbr_array[$counter]);
        foreach ($snpsToPrint as $snp) {
        	
        	fwrite($fh_genotypeFile, "\t".$arrayOfGenotypeValues[$snp][$counter]);
        	
        }
        fwrite($fh_genotypeFile, "\r");
    }
    fclose($fh_genotypeFile);
    






     /*
     * annotation file
     */

	$annotation_file = "../TXT/annotation.txt";
    $fh_annotationfile = fopen($annotation_file, 'w');
    fwrite($fh_annotationfile, "\tgenesymbol\tgenename\r");

    $probesetsToPrint = array_keys($annotationArray);
    foreach ($probesetsToPrint as $probeset) {
    	fwrite($fh_annotationfile, $probeset."\t".$annotationArray[$probeset]."\r");
    }




	system("$Rscript_path ../R/genes_vs_genotypes.R");
	
	
    $nocache = rand();
    echo "
    <td>
    <img src='../Images/genes_vs_genotype.png?$nocache'>
    </td>";
                    
                    		
					
    
   echo "</table>
   <br>
   
   <a href='../PDF/genes_vs_genotype.pdf?$nocache'>
   PDF-file with plots
   </a>
   <br>
   
   <a href='../TXT/raw_data.xls?$nocache'>
   Text file with raw data
   </a>
   </body>
   </html>";


    include 'dbclose.php';
?>